package com.tim.ying.zk.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;

public class ZKUtils {
	
	public static final String ZK_REGISTRY_PATH = "/registry";
	public static final String ZK_PROVIDER_PATH = ZK_REGISTRY_PATH+"/provider";
	private static final String ZK_CONNECTION_STRING ="127.0.0.1:2181";
	private static final Integer ZK_SESSION_TIMEOUT = 5000;
	private static CountDownLatch countDown = new CountDownLatch(1);
	
	public static ZooKeeper createServer(){
		ZooKeeper zk = null;
		try {
			zk = new ZooKeeper(ZK_CONNECTION_STRING, ZK_SESSION_TIMEOUT, new Watcher() {
				
				@Override
				public void process(WatchedEvent event) {
					if(event.getState()==Event.KeeperState.SyncConnected){
						countDown.countDown();
					}
				}
			});
		} catch (IOException e) {
			System.out.println("zk 服务器连接失败..");
			e.printStackTrace();
			return null;
		}
		try {
			countDown.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return zk;
	}
	
	public static synchronized void createPersisitentNode(ZooKeeper zk,String path,String data,List<ACL> acl){
		if(zk!=null){
			try {
				if(zk.exists(path, false)==null){
					createNode(zk, path, data, acl, CreateMode.PERSISTENT);
					System.out.println("创建永久节点成功,节点路径===>"+path);
				}
			} catch (KeeperException | InterruptedException e) {
				System.out.println("创建永久节点失败");
				e.printStackTrace();
			}
		}
	}
	
	public static String createNode(ZooKeeper zk,String path,String data,List<ACL> acl,CreateMode createMode){
		String createPath = null;
		if(zk!=null){
			try {
				byte[] b = data==null?null:data.getBytes();
				createPath = zk.create(path, b, acl, createMode);
				System.out.println("Node 创建成功 "+ createPath+" ==>"+ data);
			} catch (KeeperException | InterruptedException e) {
				System.out.println("创建节点失败...");
				e.printStackTrace();
			}
		}
		return createPath;
	}
}
